#include "libmp4v2_interface.h"
#include <arpa/inet.h>
#include <QDateTime>

libmp4v2_interface::libmp4v2_interface(QObject *parent) :
    QObject(parent)
{

    refresh_timer=new QTimer();
    connect(refresh_timer,SIGNAL(timeout()),this,SLOT(save_video_file()));
  //  refresh_timer->start(10000);
}


libmp4v2_interface::~libmp4v2_interface()
{
    delete refresh_timer;
    MP4Close(mp4File);
    MP4Optimize("20.mp4");
}

void libmp4v2_interface::open_mp4_file(const char* pathname)
{

    if( QFile::exists( pathname ) ) mp4File = MP4Modify(pathname);
    else mp4File = MP4Create(pathname);

    if (!mp4File) {
        exit(1);
    }

     MP4SetVideoProfileLevel(mp4File, 1);
     MP4SetTimeScale(mp4File, 90000);
     videoTrackId = MP4AddVideoTrack(mp4File, 90000, 90000/FPS,IMAGE_WIDTH, IMAGE_HEIGHT);

}

void libmp4v2_interface::write_one_frame(uchar* bytes,uint size)
{

//    uint32_t* p = (uint32_t*)bytes;
//    *p = htonl((uint32_t)(size -4));//大端,去掉头部3个字节

    MP4WriteSample(mp4File, videoTrackId, bytes,size,90000/FPS);
}


void libmp4v2_interface::save_video_file()
{
//    QString filename=QDateTime::currentDateTime().toString("yyMMddhh") + ".mp4";
//    QByteArray ba = filename.toLatin1();
//    open_mp4_file(ba.data());
    QByteArray frame;
    while (!encoded_frame_queue.isEmpty())
  {
    frame=encoded_frame_queue.dequeue();
    MP4WriteSample(mp4File, videoTrackId,
                   (uint8_t*)frame.data(),(uint32_t)frame.size(),90000/FPS);
    }
//     MP4Close(mp4File);

}
